<template>
  <div class="custom-tree-container">
    <el-row>
      <el-col style="width:800px">
        <div class="block">
          <div>机构</div>
          <el-tree
            :data="dataList"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>{{ data.lable }}</span>
              <span>
                <el-button
                  v-show="data.type!=='window' && data.type!='org' && data.type!='root'"
                  type="text"
                  size="mini"
                  @click="() => append(node,data)"
                >
                  添加
                </el-button>
                <el-button
                  v-show="data.type!='root' && data.type!='org'"
                  type="text"
                  size="mini"
                  @click="() =>data.type==='hall'? handleUpdateHall(node,data):handleUpdateWindow(node,data)"
                >
                  修改
                </el-button>
                <el-button
                  v-show="data.type!='root' && data.type!='org'"
                  type="text"
                  size="mini"
                  @click="() => remove(node, data)"
                >
                  删除
                </el-button>
              </span>
            </span>
          </el-tree>
        </div>
      </el-col>
    </el-row>
    <!-- 大厅新增与修改 -->
    <el-dialog :visible.sync="hallModelFlag" :title="title" width="500px">
      <el-form ref="dataForm" label-position="left" label-width="70px" style="margin:0 auto">
        <el-form-item label="大厅名称" prop="title">
          <el-input v-model="temp.hallName" />
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStatus==='create'?createHall():updateHall()">保存</el-button>
        <el-button type="primary" @click="hallModelFlag = false">取消</el-button>
      </span>
    </el-dialog>
    <!-- 窗口新增与修改 -->
    <el-dialog :visible.sync="winModelFlag" :title="title" width="600px">
      <el-form ref="dataForm" label-position="left" label-width="70px" style="margin:0 auto">
        <el-form-item label="窗口名称" prop="title">
          <el-input v-model="temp.windowName" />
        </el-form-item>
        <!-- <el-input v-model="temp.userId" /> -->
        <el-row
          type="flex"
          justify="space-between"
        >
          <el-col :span="11">
            <el-form-item label="部门" prop="title">
              <!-- <el-cascader
                style="width:100%"
                :options="DeptList"
                :props="{ expandTrigger: 'hover',value:'id',label:'label',emitPath:false}"
                @change="DepChange"
              /> -->
              <el-select v-model="depId" class="filter-item" placeholder="请选择" @change="depChange">
                <el-option
                  v-for="(item,index) in DeptList"
                  :key="index"
                  :label="item.deptName"
                  :value="item.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="选择员工" prop="title">
              <el-select v-model="temp.userId" class="filter-item" placeholder="请选择">
                <el-option
                  v-for="(item,index) in empList"
                  :key="index"
                  :label="item.userName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="绑定设备" prop="title">
          <el-select v-model="temp.devId" style="width: 140px" placeholder="绑定设备" class="filter-item" :clearable="true">
            <el-option
              v-for="(item,index) in devList"
              :key="index"
              :label="item.devName"
              :value="item.id"
            />
          </el-select>

        </el-form-item></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStatus==='create'?createWindow():updateWindow()">保存</el-button>
        <el-button type="primary" @click="winModelFlag = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getOrgTree, getByIdApi, editApi, addApi, DeleteApi, getDeptTreeByDeptId } from '@/api/sysmanage'
import { getUnboundDev, getAllUserByDeptId } from '@/api/public'
export default {
  data() {
    return {
      hallModelFlag: false,
      title: '',
      winModelFlag: false,
      listLoading: true,
      dataList: [],
      devList: [],
      temp: {},
      dialogStatus: '',
      nodeStore: '',
      dataStore: '',
      DeptList: [],
      empList: [],
      depId: ''
    }
  },
  created() {
    this.getData()
    getUnboundDev().then(res => { // 获取设备列表
      const { data } = res
      this.devList = data
    })
  },
  methods: {
    getData() {
      getOrgTree().then(response => {
        const { data } = response
        this.dataList = data
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    append(node, data) { // 开始新增窗口操作
      // 新增只能新增窗口
      this.temp = {
        'devId': 0,
        'hallId': data.id,
        'userId': 0,
        'windowName': ''
      }
      this.title = '添加窗口'
      this.winModelFlag = true// 窗口新增与修改modal
      this.dialogStatus = 'create'
      this.dataStore = data
      this.nodeStore = node
    },
    createWindow() { // 新增窗口--提交
      addApi(this.temp, 'window').then(res => {
        console.log('TCL: createWindow -> res', res)
        const { code, message, data } = res
        if (code === '200') {
          this.$message({
            message: message,
            type: 'success'
          })
          const ID = data.id
          const name = data.windowName
          const newChild = { id: ID, lable: name, type: 'window' }
          if (!this.dataStore.children) {
            this.$set(this.dataStore, 'children', [])
          }
          this.dataStore.children.push(newChild)
          this.$forceUpdate()
          this.winModelFlag = false
        } else {
          this.$message({
            message: message,
            type: 'warning'
          })
        }
      })
    },
    handleUpdateWindow(node, data) { // 开始修改窗口信息
      console.log('TCL: handleUpdateWindow -> node', node)
      console.log('TCL: handleUpdateWindow -> data', data)
      this.dataStore = data
      this.nodeStore = node
      this.temp = {
        'id': '',
        'devId': 0,
        'hallId': 0,
        'userId': 0,
        'windowName': ''
      }
      this.title = '修改窗口'
      this.dialogStatus = 'update'
      this.winModelFlag = true// 窗口新增与修改modal
      const id = data.id// 获取该窗口的ID
      getByIdApi({ id }, 'window').then(res => { // 通过窗口id获取窗口信息
        console.log('TCL: handleUpdateWindow -> res', res)
        const { data } = res
        const { id, devId, hallId, userId, windowName } = data
        this.temp = {
          'id': id,
          'devId': devId,
          'hallId': hallId,
          'userId': userId,
          'windowName': windowName
        }
      })
      const orgId = node.parent.parent.data.id// 获取该窗口对应的机构id
      this.depId = ''
      getDeptTreeByDeptId({ 'deptId': orgId }).then(res => {
        console.log('TCL: res', res)
        const { data } = res
        this.DeptList = data
      })
    },
    depChange(deptId) { // 监听选中的部门树ID，通过部门ID获取部门下所有员工
      console.log('TCL: DepChange -> deptId', deptId)
      getAllUserByDeptId({ deptId }).then(res => {
        const { data } = res
        this.empList = data
        this.temp.userId = ''
      })
    },
    updateWindow() { // 修改窗口--提交
      editApi(this.temp, 'window').then(res => {
        console.log('TCL: updateWindow -> res', res)
        const { code, message } = res
        if (code === '200') {
          this.$message({
            message: message,
            type: 'success'
          })
          this.dataStore.lable = this.temp.windowName
          this.$forceUpdate()
          this.winModelFlag = false
        } else {
          this.$message({
            message: message,
            type: 'warning'
          })
        }
      })
    },
    handleUpdateHall(node, data) {
      this.dataStore = data
      this.nodeStore = node
      this.temp = {
        'hallName': '',
        'hallSort': 0,
        'id': 0,
        'orgId': 0
      }
      this.title = '修改大厅'
      this.dialogStatus = 'update'
      this.hallModelFlag = true// 窗口新增与修改modal
      const id = data.id// 获取该窗口的ID
      getByIdApi({ id }, 'hall').then(res => { // 通过窗口id获取窗口信息
        console.log('TCL: handleUpdateWindow -> res', res)
        const { data } = res
        const { hallName, hallSort, id, orgId } = data
        this.temp = {
          'hallName': hallName,
          'hallSort': hallSort,
          'id': id,
          'orgId': orgId
        }
      })
    },
    updateHall() { // 修改大厅--提交
      editApi(this.temp, 'hall').then(res => {
        console.log('TCL: updateHall -> res', res)
        const { code, message } = res
        if (code === '200') {
          this.$message({
            message: message,
            type: 'success'
          })
          this.dataStore.lable = this.temp.hallName
          this.$forceUpdate()
          this.hallModelFlag = false
        } else {
          this.$message({
            message: message,
            type: 'warning'
          })
        }
      })
    },
    remove(node, data) {
      const { id, type } = data
      DeleteApi({ id }, type).then(res => {
        console.log('TCL: remove -> res', res)
        const { code, message } = res
        if (code === '200') {
          this.$message({
            message: message,
            type: 'success'
          })
          const parent = node.parent
          const children = parent.data.children || parent.data
          const index = children.findIndex(d => {
            d.id === data.id
          })
          children.splice(index, 1)
        } else {
          this.$message({
            message: message,
            type: 'warning'
          })
        }
      })
    }
  }
}
</script>

<style>
.custom-tree-container{
  padding:40px
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
